package com.bwie.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.pojo.Examination;
import com.bwie.service.ExaminationService;
import com.bwie.unit.MessageVo;
import com.bwie.unit.R;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class ExaminationController {

   @Autowired
   private ExaminationService examinationService;

   @Autowired
   private StringRedisTemplate stringRedisTemplate;

   @Autowired
   private RabbitTemplate rabbitTemplate;

   @PostMapping("ExaminationList")
   public R ExaminationList(@RequestBody Examination examination){
       Page<Examination> examinationPage = new Page<>(examination.getPageNum(), examination.getPageSize());
       Page<Examination> list = examinationService.listpage(examinationPage);
       stringRedisTemplate.opsForValue().set("list", String.valueOf(list),15, TimeUnit.MINUTES);
       return R.OK(list);
   }

   @PostMapping("AddEx")
   public R AddEx(@RequestBody Examination examination){
       if (examination.getExaminationNums()<=examination.getExaminationPeople()){
           return R.ERROR(500,"预约已满");
       }
       examinationService.save(examination);
       MessageVo messageVo = new MessageVo();
       String msgId = UUID.randomUUID().toString();
       messageVo.setMsgId(msgId);
       messageVo.setMsgBody(String.valueOf(examination));
       stringRedisTemplate.opsForValue().set(msgId, String.valueOf(examination),15,TimeUnit.MINUTES);
       rabbitTemplate.convertAndSend("directExchange","",JSON.toJSONString(messageVo));
       return R.OK("预约成功");
   }

   @RabbitListener(queues = "listQueue")
   public void queue(String msg, Message message, Channel channel) throws IOException {
       MessageVo messageVo = JSON.parseObject(msg, MessageVo.class);
       String msgId = messageVo.getMsgId();
       String msgBody = messageVo.getMsgBody();
       if (!stringRedisTemplate.hasKey(msgId)){
           channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
           return;
       }
       stringRedisTemplate.delete(msgId);
       channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
       return;
   }


}
